﻿#ifndef TYPESDEF_H
#define TYPESDEF_H



#include <windows.h>
#include <tlhelp32.h>
#include <QDebug>
#include <Psapi.h>
#include <tchar.h>
#include <QPixmap>
#include <QFileIconProvider>
#include <QtWinExtras/QtWinExtras>
#include <winbase.h>
#include <QFileInfo>
#include <winver.h>
#include <QFile>
#include <QFileDialog>
#include <QDate>
#include <QBuffer>
#include "ntdef.h"
#include <QItemDelegate>
#include <QFile>
#include <QFileDialog>
#include <QIODevice>
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QToolTip>

#include <QTextCodec>
#include <QDate>
#include <QDataStream>
#include <QTextStream>
#include <QMessageBox>

#include <QMainWindow>
#include <QStandardItemModel>
#include <QHeaderView>
#include <QTime>
#include <QLabel>
#include <QMouseEvent>
#include <QEvent>
#include <QMouseEvent>
#include <shellapi.h>
#include <shlobj.h>
#include <QStyledItemDelegate>
#include <QScrollBar>
#include <QInputDialog>



#define PROCESS_FLUSH_TIME 1000

#define SUSPEND_FAIL_FLAG 0XFFFFFFFF

#define SafeCloseHandle(handle) \
{                               \
    if(handle)                  \
    CloseHandle(handle);        \
    }                           \

#define SafeFree(handle)        \
{                               \
    if(handle)                  \
    free(handle);               \
    }                           \

#define SafeDelete(pBlock)      \
{                               \
    if(pBlock)                  \
    delete pBlock;              \
    }                           \



#define IDLE_PROCESS_ID 0
#define SYSTEM_PROCESS_ID 4




#define PROCESS_EXIT_CODE 0

#define STATUS_INFO_LENGTH_MISMATCH      ((NTSTATUS)0xC0000004L)
#define STATUS_ACCESS_DENIED             ((NTSTATUS)0xC0000022L)
#define STATUS_NOT_MAPPED_VIEW           ((NTSTATUS)0xC0000019L)


#define STATUS_SUCCESS 0
class ReadOnlyDelegate: public QItemDelegate
{
public:
    ReadOnlyDelegate(QWidget *parent = NULL):QItemDelegate(parent)
    {}
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const override //final
    {
        Q_UNUSED(parent)
        Q_UNUSED(option)
        Q_UNUSED(index)
        return NULL;
    }

};

class CommonDelegate : public QStyledItemDelegate
{
public:
    CommonDelegate():QStyledItemDelegate(){}
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
            QStyleOptionViewItem itemOption(option);
            if(itemOption.state&QStyle::State_HasFocus)
            {
                itemOption.state=itemOption.state^QStyle::State_HasFocus;
            }
            QStyledItemDelegate::paint(painter,itemOption,index);
    }
};



typedef enum DisassembleMode
{
    Mode32=32,
    Mode64=64
}DisassembleMode;


typedef enum FileInformation {
    Comments,
    InternalName,
    ProductName,
    CompanyName,
    LegalCopyright,
    ProductVersion,
    FileDescription,
    LegalTrademarks,
    PrivateBuild,
    FileVersion,
    OriginalFilename,
    SpecialBuild
}FileInformation;



typedef enum _SYSTEM_INFORMATION_CLASS
{
    SystemBasicInformation,
    SystemProcessorInformation,              // obsolete...delete
    SystemPerformanceInformation,
    SystemTimeOfDayInformation,
    SystemPathInformation,
    SystemProcessInformation,                //系统进程信息
    SystemCallCountInformation,
    SystemDeviceInformation,
    SystemProcessorPerformanceInformation,
    SystemFlagsInformation,
    SystemCallTimeInformation,
    SystemModuleInformation,     //系统模块
    SystemLocksInformation,
    SystemStackTraceInformation,
    SystemPagedPoolInformation,
    SystemNonPagedPoolInformation,
    SystemHandleInformation,
    SystemObjectInformation,
    SystemPageFileInformation,
    SystemVdmInstemulInformation,
    SystemVdmBopInformation,
    SystemFileCacheInformation,
    SystemPoolTagInformation,
    SystemInterruptInformation,
    SystemDpcBehaviorInformation,
    SystemFullMemoryInformation,
    SystemLoadGdiDriverInformation,
    SystemUnloadGdiDriverInformation,
    SystemTimeAdjustmentInformation,
    SystemSummaryMemoryInformation,
    SystemMirrorMemoryInformation,
    SystemPerformanceTraceInformation,
    SystemObsolete0,
    SystemExceptionInformation,
    SystemCrashDumpStateInformation,
    SystemKernelDebuggerInformation,
    SystemContextSwitchInformation,
    SystemRegistryQuotaInformation,
    SystemExtendServiceTableInformation,
    SystemPrioritySeperation,
    SystemVerifierAddDriverInformation,
    SystemVerifierRemoveDriverInformation,
    SystemProcessorIdleInformation,
    SystemLegacyDriverInformation,
    SystemCurrentTimeZoneInformation,
    SystemLookasideInformation,
    SystemTimeSlipNotification,
    SystemSessionCreate,
    SystemSessionDetach,
    SystemSessionInformation,
    SystemRangeStartInformation,
    SystemVerifierInformation,
    SystemVerifierThunkExtend,
    SystemSessionProcessInformation,
    SystemLoadGdiDriverInSystemSpace,
    SystemNumaProcessorMap,
    SystemPrefetcherInformation,
    SystemExtendedProcessInformation,
    SystemRecommendedSharedDataAlignment,
    SystemComPlusPackage,
    SystemNumaAvailableMemory,
    SystemProcessorPowerInformation,
    SystemEmulationBasicInformation,//=SystemBasicInformation
    SystemEmulationProcessorInformation,//=SystemProcessorInformation
    SystemExtendedHandleInformation,
    SystemLostDelayedWriteInformation,
    SystemBigPoolInformation,
    SystemSessionPoolTagInformation,
    SystemSessionMappedViewInformation,
    SystemHotpatchInformation,
    SystemObjectSecurityMode,
    SystemWatchdogTimerHandler,
    SystemWatchdogTimerInformation,
    SystemLogicalProcessorInformation,
    SystemWow64SharedInformation,
    SystemRegisterFirmwareTableInformationHandler,
    SystemFirmwareTableInformation,
    SystemModuleInformationEx,
    SystemVerifierTriageInformation,
    SystemSuperfetchInformation,
    SystemMemoryListInformation,
    SystemFileCacheInformationEx,

    //100?
    SystemPageMemoryInformation = 123,//自定义
    SystemPolicyInformation = 134,

} SYSTEM_INFORMATION_CLASS, * PSYSTEM_INFORMATION_CLASS;


typedef enum _THREADINFOCLASS
{
    ThreadBasicInformation,
    ThreadTimes,
    ThreadPriority,
    ThreadBasePriority,
    ThreadAffinityMask,
    ThreadImpersonationToken,
    ThreadDescriptorTableEntry,
    ThreadEnableAlignmentFaultFixup,
    ThreadEventPair_Reusable,
    ThreadQuerySetWin32StartAddress,
    ThreadZeroTlsCell,
    ThreadPerformanceCount,
    ThreadAmILastThread,
    ThreadIdealProcessor,
    ThreadPriorityBoost,
    ThreadSetTlsArrayAddress,   // Obsolete
    ThreadIsIoPending,
    ThreadHideFromDebugger,
    ThreadBreakOnTermination,
    ThreadSwitchLegacyState,
    ThreadIsTerminated,
    ThreadLastSystemCall,
    ThreadIoPriority,
    ThreadCycleTime,
    ThreadPagePriority,
    ThreadActualBasePriority,
    ThreadTebInformation,
    ThreadCSwitchMon,          // Obsolete
    ThreadCSwitchPmu,
    ThreadWow64Context,
    ThreadGroupInformation,
    ThreadUmsInformation,      // UMS
    ThreadCounterProfiling,
    ThreadIdealProcessorEx,
    MaxThreadInfoClass
} THREADINFOCLASS;



typedef struct ProcessBean {
    ULONG pId;
    ULONG parentPId;
    ULONG bit;
    ULONG64 eprocess;
    QString pName;
    ULONG threadCount;
    QString pPath;
    QString companyName;
    bool operator ==(const ProcessBean p1)
    {
        if (this->pId==p1.pId) {
            return true;
        }
        return false;
    }
} ProcessBean,* PProcessBean;


typedef struct _CLIENT_ID{
    HANDLE UniqueProcess;
    HANDLE UniqueThread;
}CLIENT_ID;


//
// Wait reasons
//

typedef enum _KWAIT_REASON {
    Executive,
    FreePage,
    PageIn,
    PoolAllocation,
    DelayExecution,
    Suspended,
    UserRequest,
    WrExecutive,
    WrFreePage,
    WrPageIn,
    WrPoolAllocation,
    WrDelayExecution,
    WrSuspended,
    WrUserRequest,
    WrSpare0,
    WrQueue,
    WrLpcReceive,
    WrLpcReply,
    WrVirtualMemory,
    WrPageOut,
    WrRendezvous,
    WrKeyedEvent,
    WrTerminated,
    WrProcessInSwap,
    WrCpuRateControl,
    WrCalloutStack,
    WrKernel,
    WrResource,
    WrPushLock,
    WrMutex,
    WrQuantumEnd,
    WrDispatchInt,
    WrPreempted,
    WrYieldExecution,
    WrFastMutex,
    WrGuardedMutex,
    WrRundown,
    WrAlertByThreadId,
    WrDeferredPreempt,
    WrPhysicalFault,
    MaximumWaitReason
} KWAIT_REASON;
typedef enum _THREAD_STATE {
    StateInitialized,
    StateReady,
    StateRunning,
    StateStandby,
    StateTerminated,
    StateWait,
    StateTransition,
    StateUnknown
} THREAD_STATE;
typedef struct _SYSTEM_THREAD_INFORMATION
{
    LARGE_INTEGER KernelTime;
    LARGE_INTEGER UserTime;
    LARGE_INTEGER CreateTime;
    ULONG WaitTime;
    PVOID StartAddress;
    CLIENT_ID ClientId;
    ULONG Priority;
    LONG BasePriority;
    ULONG ContextSwitches;
    THREAD_STATE ThreadState;
    KWAIT_REASON WaitReason;
} SYSTEM_THREAD_INFORMATION, * PSYSTEM_THREAD_INFORMATION;



typedef struct _SYSTEM_PROCESS_INFORMATION
{
    ULONG NextEntryOffset;
    ULONG NumberOfThreads;
    LARGE_INTEGER SpareLi1;
    LARGE_INTEGER SpareLi2;
    LARGE_INTEGER SpareLi3;
    LARGE_INTEGER CreateTime;
    LARGE_INTEGER UserTime;
    LARGE_INTEGER KernelTime;
    UNICODE_STRING ImageName;
    ULONG BasePriority;
    HANDLE UniqueProcessId;
    HANDLE InheritedFromUniqueProcessId;
    ULONG HandleCount;
    ULONG SessionId;
    ULONG_PTR PageDirectoryBase;
    SIZE_T PeakVirtualSize;
    SIZE_T VirtualSize;
    ULONG PageFaultCount;
    SIZE_T PeakWorkingSetSize;
    SIZE_T WorkingSetSize;
    SIZE_T QuotaPeakPagedPoolUsage;
    SIZE_T QuotaPagedPoolUsage;
    SIZE_T QuotaPeakNonPagedPoolUsage;
    SIZE_T QuotaNonPagedPoolUsage;
    SIZE_T PagefileUsage;
    SIZE_T PeakPagefileUsage;
    SIZE_T PrivatePageCount;
    LARGE_INTEGER ReadOperationCount;
    LARGE_INTEGER WriteOperationCount;
    LARGE_INTEGER OtherOperationCount;
    LARGE_INTEGER ReadTransferCount;
    LARGE_INTEGER WriteTransferCount;
    LARGE_INTEGER OtherTransferCount;
    SYSTEM_THREAD_INFORMATION Threads[1];
} SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;

typedef struct _PE_STRUCT {
    PIMAGE_DOS_HEADER dosHeader;
    PIMAGE_NT_HEADERS ntHeader;
    PIMAGE_FILE_HEADER FileHeader;
    union{
        PIMAGE_OPTIONAL_HEADER OptionalHeader;
        PIMAGE_OPTIONAL_HEADER32 OptionalHeader32;
        PIMAGE_OPTIONAL_HEADER64 OptionalHeader64;
    }u;
    PIMAGE_SECTION_HEADER SectionHeader;
}PeStruct, * PPeStruct;

typedef enum InjectType
{
    PROCESS32_DLL64,
    PROCESS64_DLL32,
    PROCESS32_DLL32,
    PROCESS64_DLL64
}InjectType;


typedef enum _SECTION_INHERIT
{
    ViewShare = 1,
    ViewUnmap = 2
} SECTION_INHERIT, *PSECTION_INHERIT;

typedef struct _IO_STATUS_BLOCK {
    union {
        NTSTATUS Status;
        PVOID    Pointer;
    } DUMMYUNIONNAME;
    ULONG_PTR Information;
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;


typedef struct _THREAD_BASIC_INFORMATION{
    LONG ExitStatus;
    PVOID TebBaseAddress;
    CLIENT_ID ClientId;
    LONG AffinityMask;
    LONG Priority;
    LONG BasePriority;
}THREAD_BASIC_INFORMATION,*PTHREAD_BASIC_INFORMATION;

typedef enum _MEMORY_INFORMATION_CLASS
{
    MemoryBasicInformation,
    MemoryWorkingSetList,
    MemorySectionName
}MEMORY_INFORMATION_CLASS;

typedef enum  SearchTypeForExportTable
{
    ByName,
    ByOrigin
}SearchTypeForExportTable;
typedef WINBOOL (*WINAPI NtTerminateThreadDef)
(HANDLE hThread, DWORD dwExitCode);


//=========================未文档化API=============================
typedef BOOL (WINAPI *DllMainCRTStartupDef)
(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved);



typedef DWORD (WINAPI *NtSuspendProcessDef)(HANDLE ProcessHandle);
typedef DWORD (WINAPI *NtResumeProcessDef)(HANDLE hProcess);
typedef NTSTATUS (*NtQueryVirtualMemoryDef)(
        _In_      HANDLE                   ProcessHandle,
        _In_opt_  PVOID                    BaseAddress,
        _In_      MEMORY_INFORMATION_CLASS MemoryInformationClass,
        _Out_     PVOID                    MemoryInformation,
        _In_      SIZE_T                   MemoryInformationLength,
        _Out_opt_ PSIZE_T                  ReturnLength
        );
typedef NTSTATUS (*ZwOpenFileDef)(
        PHANDLE            FileHandle,
        ACCESS_MASK        DesiredAccess,
        POBJECT_ATTRIBUTES ObjectAttributes,
        PIO_STATUS_BLOCK   IoStatusBlock,
        ULONG              ShareAccess,
        ULONG              OpenOptions
        );

typedef NTSTATUS (*NtCreateSectionDef)(
        OUT PHANDLE            SectionHandle,
        IN ACCESS_MASK        DesiredAccess,
        IN POBJECT_ATTRIBUTES ObjectAttributes,
        PLARGE_INTEGER     MaximumSize,
        ULONG              SectionPageProtection,
        ULONG              AllocationAttributes,
        HANDLE             FileHandle
        );
typedef NTSTATUS (*NtMapViewOfSectionDef)(
        HANDLE          SectionHandle,
        HANDLE          ProcessHandle,
        PVOID           *BaseAddress,
        ULONG_PTR       ZeroBits,
        SIZE_T          CommitSize,
        PLARGE_INTEGER  SectionOffset,
        PSIZE_T         ViewSize,
        SECTION_INHERIT InheritDisposition,
        ULONG           AllocationType,
        ULONG           Win32Protect
        );

typedef NTSTATUS(WINAPI *NtQueryInformationThreadDef)(
        HANDLE ThreadHandle,
        ULONG ThreadInformationClass,
        PVOID ThreadInformation,
        ULONG ThreadInformationLength,
        PULONG ReturnLength
        );
typedef NTSTATUS(WINAPI *NtQuerySystemInformationDef)(
        IN SYSTEM_INFORMATION_CLASS SystemInformationClass
        , OUT PVOID SystemInformation
        , IN ULONG SystemInformationLength
        , OUT PULONG ReturnLength OPTIONAL);

typedef NTSTATUS (*NtUnmapViewOfSectionDef)(
        HANDLE ProcessHandle,
        PVOID  BaseAddress
        );

typedef VOID (*RtlInitUnicodeStringDef)(
        PUNICODE_STRING         DestinationString,
        PCWSTR SourceString
        );


typedef  NTSTATUS (*NtOpenFileDef)(
        PHANDLE            FileHandle,
        ACCESS_MASK        DesiredAccess,
        POBJECT_ATTRIBUTES ObjectAttributes,
        PIO_STATUS_BLOCK   IoStatusBlock,
        ULONG              ShareAccess,
        ULONG              OpenOptions
        );
typedef NTSTATUS (*NtOpenSectionDef)(
  PHANDLE            SectionHandle,
  ACCESS_MASK        DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes
);

typedef BOOLEAN(WINAPI *RtlDosPathNameToNtPathName_UDef)
(PCWSTR DosFileName
 , PUNICODE_STRING NtFileName
 , PWSTR *FilePart
 , PVOID Reserved);


typedef BOOL (WINAPI *IsWow64ProcessDef)(
        IN  HANDLE hProcess,
        OUT PBOOL Wow64Process
        );

typedef NTSTATUS (WINAPI *LdrLoadDllDef)
(IN PWCHAR PathToFile OPTIONAL
 ,IN ULONG Flags OPTIONAL
 ,IN PUNICODE_STRING ModuleFileName
 ,OUT PHANDLE ModuleHandle);
typedef HMODULE (WINAPI *LoadLibraryADef)(LPCSTR lpLibFileName);

//==============================数据结构体======================================
typedef struct InjectData
{
    PWCHAR PathToFile;
    //加载的DLL是32位或是64位,如果是64位调用目标进程中的LdrLoadDll64,否则调用目标进程中的LdrLoadDll32
    ULONG64 Flags;
    HANDLE ModuleHandle;
    //加载64位dll 函数LdrLoadDll地址
    LdrLoadDllDef LdrLoadDll64;
    NtTerminateThreadDef TerminateThread;
    UNICODE_STRING ModuleFileName;
    UCHAR threadParam[8];
    UCHAR switchX32ToX64[8];
    WCHAR szDllPath[MAX_PATH];
}InjectData,*PInjectData;

typedef NTSTATUS(NTAPI *NtCreateThreadExDef)
(
OUT PHANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN HANDLE ProcessHandle,
IN PVOID StartRoutine,
IN PVOID StartContext,
IN ULONG Flags,
IN ULONG_PTR StackZeroBits,
IN SIZE_T StackCommit,
IN SIZE_T StackReserve,
IN PVOID  AttributeList
);
typedef struct ProcessThreadBean {
    ULONG threadId;
    ULONG64 ethread;
    ULONG64 teb;
    ULONG64 threadEntryPoint;
    ULONG Priority;
    ULONG status;
    KWAIT_REASON waitReason;
    ULONG cntUsage;
    WCHAR moudleName[MAX_PATH];
} ProcessThreadBean,* PProcessThreadBean;

//封装返回模块信息结构体
typedef struct ProcessModuleBean {
    //模块基址
    ULONG_PTR moduleAddress;
    //模块入口
    ULONG_PTR moduleEntryPoint;
    //模块大小
    ULONG moduleSize;
    //公司信息
    QString companyName;
    //模块路径
    QString modulePath;
    //重写比较方法
    bool operator ==(const ProcessModuleBean p1)
    {
//        (!QString::compare(this->moduleAddress,p1.moduleAddress,Qt::CaseInsensitive))
        if (this->moduleAddress==p1.moduleAddress)
        {
            return true;
        }
        return false;
    }
} ProcessModuleBean,* PProcessModuleBean;







//封装返回操作系统和内核版本信息的结构体
typedef struct OSVersionBean {
    //操作系统名称
    QString OSVersionName;
    //操作系统内核名称
    QString NTVersionName;
    //内核构建版本
    QString KernelBuildName;
    //操作系统SP名称
    QString SPVersionName;
} OSVersionBean,* POSVersionBean;








//结构体用于区别选中进程ID输入框的操作
typedef enum FillSelectPId
{
    RemoveProcess,//删除进程时
    InputProcessId,//输入进程ID,用于选中进程
    ClickProcessTableView//点击进程列表,选中进程
}FillSelectPId;




//指定进程进行DLL加载的ShellCode
VOID FnLoadDllShellCode(_In_ ULONG_PTR dwData);


//用于机器码转汇编代码缓冲区长度
#define AssemblyStringBufferLength 100
#define PAGE_SIZE 0x1000
#define GetFieldOffset(TYPE, MEMBER) ((ULONG_PTR)(&((TYPE *)0)->MEMBER));
//如果以OD格式分隔,汇编转换生成机器码以空格" "分隔
#define OD_SPLIT " "
//如果以非OD格式分隔,汇编转换生成机器码以逗号","分隔
#define NORMAL_SPLIT ","

#define SYS_SUFFIX ".SYS"
#define EXE_SUFFIX ".EXE"


#define CREATE_THREAD_SUSPENDED 0x0001



#endif // TYPESDEF_H
